//
//  SPBaseTableViewCell.m
//  城市2.0
//
//  Created by LSP on 2017/5/16.
//  Copyright © 2017年 NRH. All rights reserved.
//

#import "SPBaseTableViewCell.h"
#import "SPBaseViewController.h"
#import <SPFoundationCategory/SPFoundationCategory.h>
#import <SPUIKitCategory/SPUIKitCategory.h>

const CellSeparatorLineFrame cellSeparatorLineFrameDefault = {0, 0, 0, 0.7};


@interface UITableViewCell (ReadReuseIdentifier)
@property (nonatomic, readwrite, copy, nullable) NSString *reuseIdentifier;
@end
@implementation UITableViewCell (ReadReuseIdentifier)
@dynamic reuseIdentifier;
@end

@interface SPBaseTableViewCell ()
@property (nonatomic, weak, readwrite) UIView *lineView;

@end

@implementation SPBaseTableViewCell {
    BOOL _needSetSeparatorLine;
//    __weak UITableView *_tableView;
    BOOL _highlightEnabled;
    CellSeparatorLineFrame _separatorframe;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        _highlightEnabled = YES;
        
        [self setupSubviews];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    _highlightEnabled = YES;
    
    [self setupSubviews];
    
    if (_highlightEnabled) { // 可能在子类的setupSubviews中被改变
        [self configSelectedBackgroundView];
    }
    
}

- (void)configSelectedBackgroundView {
    UIView *view = [UIView new];
    view.userInteractionEnabled = NO;
    view.backgroundColor = [UIColor colorWithHexString:@"999999" alpha:.3];
    self.selectedBackgroundView = view;
}

- (void)setReuseIdentifier:(NSString *)reuseIdentifier {
    [super setReuseIdentifier:reuseIdentifier];
    
//    dispatch_async(dispatch_get_main_queue(), ^{
    [self configForReuseIdentifier:reuseIdentifier];
//    });
}

- (void)setupSubviews {
#if DEBUG
    NSLog(@"%@:子类 -> %@ 重载方法错误. %@", @"SPBaseTableViewCell", NSStringFromClass([self class]), @"***子类需重载此方法，且无需调用 [super setupSubviews]。***");
#endif
}
- (void)configForReuseIdentifier:(NSString *)reuseIdentifier {
    // 供子类重载
}

- (void)addLineView {
    if (_lineView) {
        [_lineView removeFromSuperview];
    }
    
    UIView *line = [UIView new];
    line.translatesAutoresizingMaskIntoConstraints = NO;
    
    UIColor *color = [UIColor colorWithWhite:.7 alpha:.7];
    if (@available(iOS 13.0, *)) {
        line.backgroundColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
                return [UIColor colorWithWhite:.4 alpha:.7];
            }else{
                return color;
            }
        }];
    } else {
        line.backgroundColor = color;
    }
    
    
    [self.contentView addSubview:line];
    _lineView = line;
}

- (void)addSeparatorLineAtTop {
    [self addSeparatorLineAtTop:cellSeparatorLineFrameDefault];
}
- (void)addSeparatorLineAtTop:(CellSeparatorLineFrame)frame {
    _separatorframe = frame;
    [self addLineView];
    _lineView.leftConstant = frame.leftSpacing;
    _lineView.rightConstant = frame.rightSpacing;
    _lineView.topConstant = frame.verticalSpacing;
    _lineView.heightConstant = frame.height;
    
//    // Left
//    NSLayoutConstraint *
//    constraint = [NSLayoutConstraint constraintWithItem:_lineView
//                                              attribute:(NSLayoutAttributeLeading)
//                                              relatedBy:(NSLayoutRelationEqual)
//                                                 toItem:self
//                                              attribute:NSLayoutAttributeLeading
//                                             multiplier:1
//                                               constant:frame.leftSpacing];
//    [self addConstraint:constraint];
//    // Right
//    constraint = [NSLayoutConstraint constraintWithItem:self
//                                              attribute:(NSLayoutAttributeTrailing)
//                                              relatedBy:(NSLayoutRelationEqual)
//                                                 toItem:_lineView
//                                              attribute:(NSLayoutAttributeTrailing)
//                                             multiplier:1
//                                               constant:frame.rightSpacing];
//    [self addConstraint:constraint];
//    // Top
//    constraint = [NSLayoutConstraint constraintWithItem:_lineView
//                                              attribute:(NSLayoutAttributeTop)
//                                              relatedBy:(NSLayoutRelationEqual)
//                                                 toItem:self
//                                              attribute:(NSLayoutAttributeTop)
//                                             multiplier:1
//                                               constant:frame.verticalSpacing];
//    [self addConstraint:constraint];
//    // Height
//    constraint = [NSLayoutConstraint constraintWithItem:_lineView
//                                              attribute:(NSLayoutAttributeHeight)
//                                              relatedBy:(NSLayoutRelationEqual)
//                                                 toItem:nil
//                                              attribute:(NSLayoutAttributeNotAnAttribute)
//                                             multiplier:1
//                                               constant:frame.height];
//    [_lineView addConstraint:constraint];
}

- (void)addSeparatorLineAtBottom {
    [self addSeparatorLineAtBottom:cellSeparatorLineFrameDefault];
}
- (void)addSeparatorLineAtBottom:(CellSeparatorLineFrame)frame {
    _separatorframe = frame;
    [self addLineView];
    _lineView.leftConstant = frame.leftSpacing;
    _lineView.rightConstant = frame.rightSpacing;
    _lineView.bottomConstant = frame.verticalSpacing;
    _lineView.heightConstant = frame.height;
//    // Left
//    NSLayoutConstraint *
//    constraint = [NSLayoutConstraint constraintWithItem:_lineView
//                                              attribute:(NSLayoutAttributeLeading)
//                                              relatedBy:(NSLayoutRelationEqual)
//                                                 toItem:self
//                                              attribute:NSLayoutAttributeLeading
//                                             multiplier:1
//                                               constant:frame.leftSpacing];
//    [self addConstraint:constraint];
//    // Right
//    constraint = [NSLayoutConstraint constraintWithItem:self
//                                              attribute:(NSLayoutAttributeTrailing)
//                                              relatedBy:(NSLayoutRelationEqual)
//                                                 toItem:_lineView
//                                              attribute:(NSLayoutAttributeTrailing)
//                                             multiplier:1
//                                               constant:frame.rightSpacing];
//    [self addConstraint:constraint];
//    // Top
//    constraint = [NSLayoutConstraint constraintWithItem:self
//                                              attribute:(NSLayoutAttributeBottom)
//                                              relatedBy:(NSLayoutRelationEqual)
//                                                 toItem:_lineView
//                                              attribute:(NSLayoutAttributeBottom)
//                                             multiplier:1
//                                               constant:frame.verticalSpacing];
//    [self addConstraint:constraint];
//    // Height
//    constraint = [NSLayoutConstraint constraintWithItem:_lineView
//                                              attribute:(NSLayoutAttributeHeight)
//                                              relatedBy:(NSLayoutRelationEqual)
//                                                 toItem:nil
//                                              attribute:(NSLayoutAttributeNotAnAttribute)
//                                             multiplier:1
//                                               constant:frame.height];
//    [_lineView addConstraint:constraint];
}


- (BOOL)ensureHadLoginIfFailed:(void(^)(void))failureContinue {
//    if ([[SingleClass userId] isValidString]) {
//        return YES;
//    }
//    UIViewController *vc = (id)self.nextResponder;
//    while (![vc isKindOfClass:[UIViewController class]] && vc.nextResponder) {
//        vc = (id)vc.nextResponder;
//    }
//    if ([vc isKindOfClass:[SPBaseViewController class]]) {
//        [(SPBaseViewController *)vc gotoLoginAndSuccessCallback:failureContinue];
//    }else if ([vc isKindOfClass:[UIViewController class]]) {
//        LoginVC *v = [LoginVC new];
//        v.loginComplete = failureContinue;
//
//        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:v];
//        [vc presentViewController:nav animated:YES completion:nil];
//    }
    return NO;
}





- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [self setHighlighted:selected animated:animated];
}

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
    if (!_highlightEnabled) {
        return;
    }
    UIView *view = self.selectedBackgroundView;
    
    if (animated) {
        if (highlighted) {
            view.alpha = .01;
            [self.contentView addSubview:view];
        }
        [UIView animateWithDuration:.15 delay:0 options:6
                         animations:^{
                             view.alpha = highlighted ? 1.0 : .01;
                         } completion:^(BOOL finished) {
                             if (!highlighted) {
                                 view.alpha = 1.;
                                 [view removeFromSuperview];
                             }
                         }];
    }else{
        if (highlighted) {
            [self.contentView addSubview:view];
        }else{
            [view removeFromSuperview];
        }
    }
}

- (void)setIsTheLastInSection:(BOOL)isTheLastInSection {
    if (_separatorframe.leftSpacing != 0) {
        self.lineView.leftConstant = (isTheLastInSection ? 0 : _separatorframe.leftSpacing);
    }
    if (_separatorframe.rightSpacing != 0) {
        self.lineView.rightConstant = (isTheLastInSection ? 0 : _separatorframe.rightSpacing);
    }
}
@end
